const prisma = require('../utils/prisma');
const { hashPassword } = require('../utils/password');
const { success, error } = require('../utils/response');

/**
 * 获取用户列表
 * @route GET /api/users
 */
const getUsers = async (req, res) => {
  try {
    const users = await prisma.user.findMany({
      select: {
        id: true,
        name: true,
        phone: true,
        avatar: true,
        role: true,
        createdAt: true
      }
    });
    
    return success(res, users);
  } catch (err) {
    console.error('Get users error:', err);
    return error(res, 'Failed to get users', 500);
  }
};

/**
 * 获取指定用户
 * @route GET /api/users/:id
 */
const getUserById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const user = await prisma.user.findUnique({
      where: { id },
      select: {
        id: true,
        name: true,
        phone: true,
        avatar: true,
        role: true,
        createdAt: true
      }
    });
    
    if (!user) {
      return error(res, 'User not found', 404);
    }
    
    return success(res, user);
  } catch (err) {
    console.error('Get user error:', err);
    return error(res, 'Failed to get user', 500);
  }
};

/**
 * 创建用户
 * @route POST /api/users
 */
const createUser = async (req, res) => {
  try {
    const { name, phone, password, role } = req.body;
    
    if (!name || !phone || !password) {
      return error(res, 'Name, phone and password are required', 400);
    }
    
    // 检查手机号是否已存在
    const existingUser = await prisma.user.findUnique({
      where: { phone }
    });
    
    if (existingUser) {
      return error(res, 'Phone number already registered', 409);
    }
    
    // 哈希密码
    const hashedPassword = await hashPassword(password);
    
    // 创建用户
    const user = await prisma.user.create({
      data: {
        name,
        phone,
        password: hashedPassword,
        role: role || 'user'
      }
    });
    
    return success(res, {
      id: user.id,
      name: user.name,
      phone: user.phone,
      role: user.role,
      createdAt: user.createdAt
    }, 'User created successfully', 201);
  } catch (err) {
    console.error('Create user error:', err);
    return error(res, 'Failed to create user', 500);
  }
};

/**
 * 更新用户
 * @route PUT /api/users/:id
 */
const updateUser = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, phone, password, avatar, role } = req.body;
    
    // 检查用户是否存在
    const existingUser = await prisma.user.findUnique({
      where: { id }
    });
    
    if (!existingUser) {
      return error(res, 'User not found', 404);
    }
    
    // 如果更新手机号，检查是否已被使用
    if (phone && phone !== existingUser.phone) {
      const phoneExists = await prisma.user.findUnique({
        where: { phone }
      });
      
      if (phoneExists) {
        return error(res, 'Phone number already in use', 409);
      }
    }
    
    // 准备更新数据
    const updateData = {};
    
    if (name) updateData.name = name;
    if (phone) updateData.phone = phone;
    if (avatar) updateData.avatar = avatar;
    if (role) updateData.role = role;
    
    // 如果更新密码，需要哈希处理
    if (password) {
      updateData.password = await hashPassword(password);
    }
    
    // 更新用户
    const updatedUser = await prisma.user.update({
      where: { id },
      data: updateData,
      select: {
        id: true,
        name: true,
        phone: true,
        avatar: true,
        role: true,
        updatedAt: true
      }
    });
    
    return success(res, updatedUser, 'User updated successfully');
  } catch (err) {
    console.error('Update user error:', err);
    return error(res, 'Failed to update user', 500);
  }
};

/**
 * 删除用户
 * @route DELETE /api/users/:id
 */
const deleteUser = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查用户是否存在
    const existingUser = await prisma.user.findUnique({
      where: { id }
    });
    
    if (!existingUser) {
      return error(res, 'User not found', 404);
    }
    
    // 删除用户
    await prisma.user.delete({
      where: { id }
    });
    
    return success(res, null, 'User deleted successfully');
  } catch (err) {
    console.error('Delete user error:', err);
    return error(res, 'Failed to delete user', 500);
  }
};

/**
 * 获取家庭成员列表
 * @route GET /api/users/family
 */
const getFamilyMembers = async (req, res) => {
  try {
    // 获取角色为 'family' 的用户
    const familyMembers = await prisma.user.findMany({
      where: { role: 'family' },
      select: {
        id: true,
        name: true,
        avatar: true,
        createdAt: true
      }
    });
    
    return success(res, familyMembers);
  } catch (err) {
    console.error('Get family members error:', err);
    return error(res, 'Failed to get family members', 500);
  }
};

module.exports = {
  getUsers,
  getUserById,
  createUser,
  updateUser,
  deleteUser,
  getFamilyMembers
};
